<template>
	<view class="container">
		<view class="header">
			<view class="title">我的收藏</view>
			<view class="filter-section">
				<view 
					class="filter-item" 
					v-for="(item, index) in filterOptions" 
					:key="index"
					:class="{'active': currentFilter === item.value}"
					@click="changeFilter(item.value)"
				>
					{{item.label}}
				</view>
			</view>
		</view>
		
		<view class="empty-box" v-if="favoriteList.length === 0">
			<image class="empty-icon" src="/static/images/empty-box.png" mode="aspectFit"></image>
			<text class="empty-text">暂无收藏内容</text>
		</view>
		
		<scroll-view scroll-y class="favorite-list" v-else>
			<!-- 规则收藏列表 -->
			<view class="favorite-item" v-for="(item, index) in favoriteList" :key="index" @click="openDetail(item)">
				<view class="item-content">
					<view class="item-title">
						<template v-if="item.title">{{item.title}}</template>
						<template v-else>未知内容</template>
					</view>
					<view class="item-summary" v-if="item.summary">{{item.summary}}</view>
					<view class="item-meta">
											<text class="item-type" v-if="item.content_type === 'rule'">规则</text>
					<text class="item-date">{{formatDate(item.create_date)}}</text>
					</view>
				</view>
				
				<view class="item-actions">
					<view class="action-btn" @click.stop="cancelFavorite(item)">
						<text class="action-icon">×</text>
					</view>
				</view>
			</view>
		</scroll-view>
		
		<!-- 加载更多 -->
		<view class="load-more" v-if="favoriteList.length > 0 && hasMore">
			<text class="load-text" @click="loadMore">加载更多</text>
		</view>
		
		<!-- 底部提示 -->
		<view class="bottom-tip" v-if="favoriteList.length > 0 && !hasMore">
			<text class="tip-text">没有更多内容了</text>
		</view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				filterOptions: [
					{label: '全部', value: 'all'},
					{label: '规则', value: 'rule'}
				],
				currentFilter: 'all',
				favoriteList: [],
				page: 1,
				pageSize: 10,
				hasMore: true,
				isLoading: false
			}
		},
		onLoad() {
			// 获取收藏列表
			this.getFavoriteList();
		},
		onPullDownRefresh() {
			// 下拉刷新
			this.refreshFavoriteList();
		},
		methods: {
			// 下拉刷新收藏列表
			refreshFavoriteList() {
				console.log('开始下拉刷新收藏列表');
				
				// 重置分页
				this.page = 1;
				this.favoriteList = [];
				this.hasMore = true;
				
				// 重新获取收藏列表
				this.getFavoriteList(false).then(() => {
					uni.showToast({
						title: '刷新成功',
						icon: 'success',
						duration: 1500
					});
				}).catch((error) => {
					console.error('刷新收藏列表失败', error);
					uni.showToast({
						title: '刷新失败',
						icon: 'none',
						duration: 1500
					});
				}).finally(() => {
					// 停止下拉刷新动画
					uni.stopPullDownRefresh();
				});
			},
			
			// 获取收藏列表
			getFavoriteList(loadMore = false) {
				if (this.isLoading) return Promise.resolve();
				
				this.isLoading = true;
				
				if (!loadMore) {
					uni.showLoading({
						title: '加载中...'
					});
				}
				
				return new Promise(async (resolve, reject) => {
					try {
						// 获取token
						const token = uni.getStorageSync('user_token');
						console.log('当前token:', token);
						
						// 调用云对象获取收藏列表
						const interactionService = uniCloud.importObject('interaction-service');
						const res = await interactionService.getFavoriteList({
							page: this.page,
							pageSize: this.pageSize,
							type: this.currentFilter === 'all' ? '' : this.currentFilter,
							token: token
						});
						
						console.log('收藏返回数据:', JSON.stringify(res));
						if (res.code === 0) {
							const data = res.data;
							
							if (loadMore) {
								this.favoriteList = [...this.favoriteList, ...data.list];
							} else {
								this.favoriteList = data.list;
							}
							
							this.hasMore = data.total > this.page * this.pageSize;
							resolve(data);
						} else {
							// 如果云对象不可用，使用模拟数据
							console.error('获取收藏失败:', res.message);
							this.getMockFavoriteList(loadMore);
							resolve();
						}
						
						this.isLoading = false;
						uni.hideLoading();
					} catch (err) {
						console.error('获取收藏列表失败', err);
						// 如果云对象不可用，使用模拟数据
						this.getMockFavoriteList(loadMore);
						
						this.isLoading = false;
						uni.hideLoading();
						reject(err);
					}
				});
			},
			
			// 获取模拟收藏列表
			getMockFavoriteList(loadMore = false) {
				// 模拟数据
				const mockData = [
					{
						_id: '1',
						content_id: '101',
						content_type: 'rule',
						title: '足球比赛规则 - 规则一：球场',
						create_date: new Date('2023-06-15').getTime()
					},
					{
						_id: '2',
						content_id: '102',
						content_type: 'rule',
						title: '足球比赛规则 - 规则二：球',
						create_date: new Date('2023-06-16').getTime()
					},

				];
				
				// 根据筛选条件过滤
				let filteredData = mockData;
				if (this.currentFilter !== 'all') {
					filteredData = mockData.filter(item => item.content_type === this.currentFilter);
				}
				
				// 模拟分页
				const startIndex = (this.page - 1) * this.pageSize;
				const endIndex = startIndex + this.pageSize;
				const pageData = filteredData.slice(startIndex, endIndex);
				
				if (loadMore) {
					this.favoriteList = [...this.favoriteList, ...pageData];
				} else {
					this.favoriteList = pageData;
				}
				
				this.hasMore = endIndex < filteredData.length;
			},
			
			// 切换筛选条件
			changeFilter(filter) {
				if (this.currentFilter === filter) return;
				
				this.currentFilter = filter;
				this.page = 1;
				this.favoriteList = [];
				this.hasMore = true;
				this.getFavoriteList();
			},
			
			// 加载更多
			loadMore() {
				if (!this.hasMore || this.isLoading) return;
				
				this.page++;
				this.getFavoriteList(true);
			},
			
			// 取消收藏
			cancelFavorite(item) {
				uni.showModal({
					title: '提示',
					content: '确定要取消收藏吗？',
					success: (res) => {
						if (res.confirm) {
							this.removeFavoriteItem(item);
						}
					}
				});
			},
			
			// 移除收藏项
			async removeFavoriteItem(item) {
				try {
					// 获取token
					const token = uni.getStorageSync('user_token');
					console.log('取消收藏的内容:', JSON.stringify(item));
					
					// 调用云对象取消收藏
					const interactionService = uniCloud.importObject('interaction-service');
					const res = await interactionService.toggleFavorite({
						contentId: item.content_id,
						contentType: item.content_type,
						token: token
					});
					
					console.log('取消收藏结果:', JSON.stringify(res));
					if (res.code === 0) {
						// 从列表中移除
						const index = this.favoriteList.findIndex(i => i._id === item._id);
						if (index !== -1) {
							this.favoriteList.splice(index, 1);
						}
						
						uni.showToast({
							title: '已取消收藏',
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: '操作失败',
							icon: 'none'
						});
					}
				} catch (err) {
					console.error('取消收藏失败', err);
					uni.showToast({
						title: '操作失败',
						icon: 'none'
					});
				}
			},
			
			// 打开详情页
			openDetail(item) {
				let url = '';
				
				if (item.content_type === 'rule') {
					url = `/packageStudy/study/rule-detail?id=${item.content_id}`;
				}
				
				if (url) {
					uni.navigateTo({
						url: url
					});
				}
			},
			
			// 格式化日期
			formatDate(timestamp) {
				if (!timestamp) return '';
				
				const date = new Date(timestamp);
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				
				return `${year}-${month}-${day}`;
			},
			
			// 跳转到调试页面
			goToDebug() {
				uni.navigateTo({
					url: '/pages/my/favorite-debug'
				});
			}
		},
		// 下拉刷新
		onPullDownRefresh() {
			this.page = 1;
			this.favoriteList = [];
			this.hasMore = true;
			this.getFavoriteList();
			
			setTimeout(() => {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		// 触底加载更多
		onReachBottom() {
			this.loadMore();
		}
	}
</script>

<style>
	.container {
		min-height: 100vh;
		background-color: #F5F5F5;
		display: flex;
		flex-direction: column;
		width: 100%;
	}
	
	/* 头部样式 */
	.header {
		background-color: #FFFFFF;
		padding: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		width: 100%;
		box-sizing: border-box;
		margin-bottom: 20rpx;
	}
	
	.title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333333;
		margin-bottom: 30rpx;
		word-wrap: break-word;
		word-break: break-all;
		display: block;
	}
	
	.filter-section {
		display: flex;
		border-bottom: 1rpx solid #EEEEEE;
		flex-wrap: wrap;
		width: 100%;
	}
	
	.filter-item {
		padding: 20rpx 30rpx;
		font-size: 28rpx;
		color: #666666;
		position: relative;
	}
	
	.filter-item.active {
		color: #1BAE76;
		font-weight: bold;
	}
	
	.filter-item.active::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 30rpx;
		right: 30rpx;
		height: 4rpx;
		background-color: #1BAE76;
		border-radius: 2rpx;
	}
	
	/* 空状态样式 */
	.empty-box {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		padding: 100rpx 0;
	}
	
	.empty-icon {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 30rpx;
	}
	
	.empty-text {
		font-size: 28rpx;
		color: #999999;
	}
	
	/* 收藏列表样式 */
	.favorite-list {
		flex: 1;
		padding: 20rpx 30rpx;
		width: 100%;
		box-sizing: border-box;
	}
	
	.favorite-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		background-color: #FFFFFF;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		width: 100%;
		box-sizing: border-box;
		flex-wrap: wrap;
	}
	
	.item-content {
		flex: 1;
		margin-right: 20rpx;
		word-wrap: break-word;
		word-break: break-all;
		min-width: 60%;
	}
	
	.item-title {
		font-size: 30rpx;
		color: #333333;
		margin-bottom: 10rpx;
		line-height: 1.4;
		word-wrap: break-word;
		word-break: break-all;
	}
	
	.item-summary {
		font-size: 24rpx;
		color: #999999;
		margin-bottom: 10rpx;
	}
	
	.item-meta {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
	}
	
	.item-type {
		font-size: 24rpx;
		color: #1BAE76;
		background-color: rgba(0, 127, 79, 0.1);
		padding: 4rpx 16rpx;
		border-radius: 20rpx;
		margin-right: 20rpx;
		margin-bottom: 10rpx;
	}
	
	.item-date {
		font-size: 24rpx;
		color: #999999;
	}
	
	.item-actions {
		display: flex;
	}
	
	.action-btn {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 30rpx;
		background-color: #F0F0F0;
	}
	
	.action-icon {
		font-size: 32rpx;
		color: #666666;
		font-weight: bold;
	}
	
	/* 加载更多样式 */
	.load-more {
		text-align: center;
		padding: 30rpx 0;
	}
	
	.load-text {
		font-size: 28rpx;
		color: #1BAE76;
	}
	
	/* 底部提示样式 */
	.bottom-tip {
		text-align: center;
		padding: 30rpx 0;
	}
	
	.tip-text {
		font-size: 24rpx;
		color: #999999;
	}
	
	.debug-btn {
		padding: 20rpx 40rpx;
		font-size: 28rpx;
		color: #FFFFFF;
		background-color: #1BAE76;
		border-radius: 40rpx;
	}
</style> 